<?php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\BrowserKit\Client;
use Symfony\Component\BrowserKit\Response;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\HttpFoundation\Response as HttpResponse;
use App\Service\ContentParser;
use App\Service\TaxonomiesManager;
use App\Util\Topic;
use App\Util\FileWriter;

class HomeController extends AbstractController
{
    /**@var ContentParser */
    private $parser;

    /**@var TaxonimiesManager */
    private $taxonomiesManager;

    public function __construct(ContentParser $parser, TaxonomiesManager $taxonomiesManager)
    {
        $this->parser = $parser;
        $this->taxonomiesManager = $taxonomiesManager;
    }

    public function index()
    {
        //$taxonomies = $this->getParameter('taxonomies');
        $taxonomies = $this->taxonomiesManager->getTaxonomies();
        ksort($taxonomies);
        foreach ($taxonomies as &$tags) {
            if (!is_array($tags)) {
                $tags = (array) $tags;        
            }
            sort($tags);
        }
        return $this->render('base.html.twig',
            ['taxonomies' => $taxonomies]
        );
    }

    public function scrap(Request $request)
    {
        if (!empty($url = $request->get('url'))) {
            $userAgent = $this->getParameter('user_agent');
            $client = new class($userAgent) extends Client
            {
                private $userAgent;
                
                public function __construct(string $userAgent)
                {
                    parent::__construct();
                    $this->userAgent = $userAgent;
                }
                /**
                 * @param object $request
                 * @return object|Response
                 */
                public function doRequest($request)
                {
                    $ch = curl_init();
                    // Set URL and other appropriate options
                    curl_setopt($ch, CURLOPT_URL, $request->getUri());
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                    curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
                    curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
                    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                    // Grab URL and pass it to the browser
                    $content = curl_exec($ch);
                    // Close cURL resource, and free up system resources
                    curl_close($ch);
                    return new Response($content);
                }
            };

            /**@var Crawler $crawler */
            $crawler = $client->request('GET', $url);
            /**@var Topic */
            if (($topic = $this->parser->parseFromCrawler($crawler, $request->get('category'))) instanceof Topic) {
                $content = $this->renderView('markdown.html.twig', [
                    'title'      => $topic->getTitle(),
                    'date'       => date('Y-m-d H:i:s'),
                    'categories' => implode(',', $topic->getCategories()),
                    'tags'       => implode(',', $topic->getTags()),
                    'content'    => $topic->getContent(),
                    'link'       => $url,
                    'parse_html' => true
                ]);
                return new HttpResponse($content);
            }
        }
        return new HttpResponse(json_encode(error_get_last()), HttpResponse::HTTP_INTERNAL_SERVER_ERROR);
    }

    public function saveMarkdown(Request $request)
    {
        if ($content = $request->get('markdown')) {
            $savePath = getenv('SAVE_PATH');
            if (preg_match('/categories:\s*\[(.*)\]/', $content, $matches)) {
                $savePath .= '/' . str_replace(' ', '-', $matches[1]);
            }
            if (preg_match('/title:\s*(.*)/', $content, $matches)) {
                $savePath .= '/' . trim($matches[1]) . '.md';
            }
            if ((new FileWriter($savePath, $content))->save()) {
                return new HttpResponse($savePath);
            }
            return new HttpResponse(error_get_last(), 500);
        }
        return new HttpResponse();
    }
}
